// ======================================================================================
// CLASS ExtensionFilter
// Filters file chooser allowing only certain file extensions
// ======================================================================================

import java.io.*;
import javax.swing.*;

public class ExtensionFilter extends javax.swing.filechooser.FileFilter {

	private	String		allow[]		=null;
	private	int		aPtr;
	private final int	MAX_EXTENSIONS	=50;
	private	JFileChooser	jfc;
	private String		filterName;
	
// --------------------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------------------

	public ExtensionFilter(String fName) {
		initialise(fName);
	}
	public ExtensionFilter(String fName,String s) {
		initialise(fName);
		add(s);
	}
	public ExtensionFilter(String fName,String s1,String s2) {
		initialise(fName);
		add(s1);
		add(s2);
	}
	public ExtensionFilter(String fName,String s1,String s2,String s3) {
		initialise(fName);
		add(s1);
		add(s2);
		add(s3);
	}
	public ExtensionFilter(String fName,String s[]) {
		initialise(fName);
		aPtr=0;
		for (int i=0;i<s.length;i++) { add(s[i]); }
	}
	
	private void initialise(String fName) {
		aPtr=0;
		jfc=new JFileChooser();
		filterName=fName;
	}

// --------------------------------------------------------------------------------------
// add():  Add an extension to the allowed list
// --------------------------------------------------------------------------------------

	public void add(String extension) {
		extension=extension.toUpperCase();
		if (allow==null) { allow=new String[MAX_EXTENSIONS]; }
		allow[aPtr++]=extension;
	}

// --------------------------------------------------------------------------------------
// accept():  Returns whether or not a file should be accepted
// --------------------------------------------------------------------------------------

	public boolean accept(File f) {
		boolean OK=((allow==null) ||
			    (jfc.getTypeDescription(f).compareTo("Directory")==0)
			    );
		if (!OK) {
			String ext=jfc.getName(f).toUpperCase();
			int pos=ext.lastIndexOf(".");
			if (pos>=0) { ext=ext.substring(pos+1); }
			else        { ext="";                   }
			for (int i=0;(i<aPtr) && (!OK);i++) {
				OK=(allow[i].compareTo(ext)==0);
			}
		}
		return OK;
	}

// --------------------------------------------------------------------------------------
// getDescription():  Return description of this filter
// --------------------------------------------------------------------------------------

	public String getDescription() { return filterName; }
}